#include "KList.h"

KList::Node::Node(Node *p, Node *n) : m_next(n), m_prev(p)
{
}

KList::Node::~Node()
{
}

KList::KList(size_t max): m_back(NULL), m_front(NULL), m_max(max), m_size(0)
{
}

KList::NodePtr KList::cutOffUnlocked(NodePtr node)
{
    if (node) {
        assert(m_size > 0);
        --m_size;
        node->m_next && (node->m_next->m_prev = node->m_prev);
        node->m_prev && (node->m_prev->m_next = node->m_next);
        node == m_back && (m_back = node->m_prev);
        node == m_front && (m_front = node->m_next);
        node->m_next = node->m_prev = NULL;
    }
    return node;
}

void KList::pushBackUnlocked(NodePtr node)
{
    assert(node != NULL);
    if (m_max == 0 || m_max > m_size) {
        node->m_next = NULL;
        if ((node->m_prev = m_back)) {
            m_back->m_next = node;
        } else {
            m_front = node;
        }
        m_back = node;
        ++m_size;
    } else {
        delete node;
    }
}

void KList::pushFrontUnlocked(NodePtr node)
{
    assert(node != NULL);
    if (m_max == 0 || m_max > m_size) {
        node->m_prev = NULL;
        if ((node->m_next = m_front)) {
            m_front->m_prev = node;
        } else {
            m_back = node;
        }
        m_front = node;
        ++m_size;
    } else {
        delete node;
    }
}